import { ReloadOutlined } from '@ant-design/icons';
import { Card, Table } from 'antd';
import React, { useRef, useState } from 'react';
import ColumnsFilter from '../../../ColumnsFilter';
import styles from './index.less';

function ScollTable(props: any) {
  const {
    listData,
    loading,
    handleChangePage,
    setCheckedIds,
    colums,
    toolBar = [],
    optional,
    reload,
    setPage,
  } = props;

  const [tableColums, setTableColumns] = useState(colums);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const rowSelection = {
    selectedRowKeys,
    onChange: (selected: any) => {
      setSelectedRowKeys(selected);
      setCheckedIds(selected);
      // setCheckedLists(selected);
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.this_year_is_lock === 1,
    }),
  };

  const options = colums.map((item: any) => item.title);

  const ref = useRef<any>();

  const [oldHeight, setOldHeight] = useState(0);

  const onScrollEvent = () => {
    if (loading) return;
    const tableBody = (ref.current as Element)?.querySelector('.ant-table-body');
    // console.log("this is tableBody", tableBody);
    // console.log("this is ref", ref.current);

    // 容器可视区高度
    const tableBodyHeight: number = tableBody!.clientHeight;
    // 内容高度
    const contentHeight = tableBody?.scrollHeight || 0;
    // 滚动条到顶部的垂直高度 (即网页被卷上去的高度)
    const toTopHeight = tableBody?.scrollTop || 0;

    if (oldHeight === toTopHeight) {
      setOldHeight(toTopHeight);
      return;
    }
    console.log('toTopHeight', toTopHeight);
    console.log('tableBodyHeight', tableBodyHeight);
    console.log('contentHeight', contentHeight);

    if (contentHeight - (toTopHeight + tableBodyHeight) <= 1) {
      setPage((pre: any) => {
        return {
          ...pre,
          current: pre.current + 1,
        };
      });
    }
  };

  return (
    <Card bordered={false} className={styles['table-card']}>
      <div style={{ marginBottom: 5, marginTop: 10, float: 'right' }}>
        <ReloadOutlined onClick={reload} className={styles['table-refresh']} />
        <ColumnsFilter
          setTableColumns={setTableColumns}
          options={options}
          columns={colums}
          style={{ marginRight: '10px' }}
          type="icon"
        />
        {toolBar.map((item: any) =>
          React.cloneElement(
            item,
            { key: item.index, className: styles.toolButton },
            item.props.children,
          ),
        )}
      </div>
      <div onScrollCapture={onScrollEvent}>
        <Table
          ref={ref}
          bordered
          loading={loading}
          dataSource={listData?.data}
          columns={tableColums}
          pagination={false}
          scroll={{ x: 10, y: 600 }}
          onChange={handleChangePage}
          rowSelection={optional ? rowSelection : undefined}
          rowKey="id"
        />
      </div>
    </Card>
  );
}
export default ScollTable;
